package com.study.lihan.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: lihan
 * @Date : 2022/1/12- 01
 * @DESCRIPTION: com.study.lihan.io
 * @version: 1.0
 */
public class SocketMultiplexMultiThreads {
    private ServerSocketChannel server ;
    private Selector selector1 ;
    private Selector selector2 ;
    private Selector selector3 ;
    int port =9090;
    public static void main(String[] args) {
        SocketMultiplexMultiThreads service = new SocketMultiplexMultiThreads();
        service.initServer();
        NioThread t1 = new NioThread(service.selector1,2);

        NioThread t2 = new NioThread(service.selector2);
        NioThread t3 = new NioThread(service.selector3);

        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();
        t3.start();
        System.out.println("服务器启动了。。。");
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public void initServer(){
        try {
            server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress(port));

            selector1 = Selector.open();
            selector2 = Selector.open();
            selector3 = Selector.open();
            server.register(selector1, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
class NioThread extends  Thread{
    Selector selector;
    static  int selectors =0;
    int id =0;
    boolean isboss = false;
    static BlockingQueue<SocketChannel>[] deques;
    static AtomicInteger idx = new AtomicInteger();
    NioThread(Selector selector,int n){ // boss
        this.selector = selector;

        this.selectors =n;
        isboss = true;
        deques = new LinkedBlockingQueue[selectors];
        for (int i = 0; i < n ; i++) {
            deques[i] = new LinkedBlockingQueue<>();
        }
        System.out.println("boss 启动");

    }
    NioThread(Selector selector){
        this.selector = selector;
        id = idx.getAndIncrement() % selectors;
        System.out.println("worker："+ id + "启动");
    }

    @Override
    public void run() {
        try {
            while (true){
                while (selector.select(10)>0){
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
//boss走这一步
                        if(key.isAcceptable()){
//boss把client放入队列
                            acceptHandler(key);
//worker走这一步
                        }else if(key.isReadable()){
                            readHanlder(key);
                        }
                    }
                }
//worker进行注册
                if(!deques[id].isEmpty() && !isboss){ //boss不参与
                    ByteBuffer allocate = ByteBuffer.allocate(8192);
                    SocketChannel client = deques[id].take();
                    client.register(selector,SelectionKey.OP_READ,allocate);
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    System.out.println("新客户端："+client.socket().getPort()+ "分配到worker："+id );
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void acceptHandler(SelectionKey key){

        try {
            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
            SocketChannel client = channel.accept();
            client.configureBlocking(false);
            int num = idx.getAndIncrement() % selectors;
            deques[num].add(client);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readHanlder(SelectionKey key){

        SocketChannel client = (SocketChannel) key.channel();
        ByteBuffer buffer = (ByteBuffer) key.attachment();

        buffer.clear();
        int read =0;
        try {
            while (true){
                read = client.read(buffer);
//如果客户端突然断开连接，返回- 1
                if(read > 0){
                    buffer.flip();
                    while (buffer.hasRemaining()){
                        client.write(buffer);
                    }
                    buffer.clear();
                }else if(read ==0){
                    break;
                }else {// -1 ,客户端关闭，isread（）一直为真
                    client.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}